<template>
    <el-container  class="height100    domainMainContent containerHeight">
    <el-main class="el-mainContent  height100 overflowYHidden"   ref="managerMain">
      <header_item  :headerArr="headerArr"  @onBtnClick="onBtnClick"/>
    <div  class="width100 overflowy containerContentHeight">
      <el-form
        ref="form"
        :model="content"
        label-position="top"
        label-width="180px"
        size="mini"
        :rules="rules"
        class="content"
      >
      <el-row>
       <el-col :span="6">
        <el-row>
            <el-form-item :label="$t('enterprise_name')"   prop="name">
              <el-input v-model="content.name"></el-input>
            </el-form-item>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item  :label="$t('systemName')" >
              <el-input v-model="content.systemName"></el-input>
            </el-form-item>
            <el-form-item class="switchItem">
              <span class="greyColor marginR34">{{$t('status')}}</span>
              <el-switch v-model="status"></el-switch>
            </el-form-item>
            <template v-if="!($store.state.currentUser && $store.state.currentUser.isOpenSecurity)">
              <el-form-item class="switchItem">
                <span class="greyColor  marginR34">{{$t('is_open_sanyuan')}}</span>
                <el-switch v-model="content.isOpenThM"></el-switch>
                <div class="greenColor miniFontSize">{{$t('msg_close_or_open')}}</div>
              </el-form-item>  
            </template>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item :label="$t('superior')">
             <div>
              <el-button size="small" @click="handleClick">{{$t('setSuperior')}}</el-button>
              <div class="marginT8">
                <el-tag
                  v-for="tag in superiorTags"
                  :key="tag.domainname"
                  size="small"
                  closable
                  @close="handleClose(tag.domainid,'parent')">
                  {{tag.domainname}}
                </el-tag></div>
             </div>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="4" v-if="childsTags && childsTags.length>0">
            <el-form-item :label="$t('subordinate')"  >
              <div>
                <el-tag
                  v-for="tag in childsTags"
                  :key="tag.domainname"
                  size="small"
                  closable
                  @close="handleClose(tag.domainid,'child')"
                  >
                  {{tag.domainname}}
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-col>
      <el-col  :span="6" :offset="4">
          <el-row>
            <el-col>
            <el-form-item label="Logo(60 x 60)："  >
              <input type="hidden" name="content.logoUrl" value />
              <input type="hidden" id="logo" name="content.logoUrl" />
              <div class="adminLogo d-inlineBlock" v-if="logoUrl=='img'">
                <img class="verticalBottom adminLogoImg" id="_iconImg" alt :src="content.logoUrl" v-if="content.logoUrl!=''"/>
                <i v-else class="el-icon-plus" @click="selectIcon"></i>
              </div>
              <div class="logoBtn" style="display: inline-block;">
                <el-button class="obpm-btn-default bluebgColor" plain @click="selectIcon" type="primary">{{$t('choose')}}</el-button>
                <el-button type="danger" plain @click="cleanIcon" class="redBgColor">{{$t('clean')}}</el-button>
              </div>
            </el-form-item>
          </el-col>
          </el-row>
          <el-row>
            <el-col>
            <el-form-item :label="$t('description')"  >
              <el-input 
                type="textarea" 
                v-model="content.description"
                placeholder="请输入内容"
                maxlength="200"
                show-word-limit
                class="textAreaInfo"
              ></el-input>
            </el-form-item>
          </el-col>
          </el-row>
      </el-col>
      </el-row>

        <!-- <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item class="marginBot0">
              <span class="greyColor">{{$t('smsMemberCode')}}</span>
              <span><a
                href="http://sms.teemlink.com/sms/register/register.jsp"
                target="_blank"
                class="tip-text"
              >[{{$t('noAccount')}}]</a></span>
              <el-input v-model="content.smsMemberCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="4">
            <el-form-item class="marginBot0">
              <span class="greyColor">{{$t('smsMemberPwd')}}</span>
              <span><a
                href="http://sms.teemlink.com/sms/"
                target="_blank"
                class="tip-text"
              >[{{$t('wantToChangePwd')}}]</a></span>
              <el-input type="password" v-model="content.smsMemberPwd" style="width: 65%"></el-input>
              <el-button
                type="primary"
                plain
                class="obpm-btn obpm-btn-default"
                @click="testSMS"
              >{{$t('testSMS')}}</el-button>
            </el-form-item>
          </el-col>
        </el-row> -->

        <extend_flex 
          :contextPath="contextPath"
          :fieldextends="fieldextends"
          :content="content"
        />
      </el-form>
      <icon_select
        :visible.sync="iconSelectCheck"
        :logoUrl="content.logoUrl"
        @select-ok="onSelectIconOk"
        v-if="iconSelectCheck"
      />
      <setting_domain
        v-if="domainVisible"
        :visible.sync="domainVisible"
        :dialogTitle="dialogTitle"
        :parentList="parentList"
        :fieldextends="fieldextends"
        @selectChecked="selectChecked"
      />
    </div>
    </el-main>

  </el-container>
</template>
<script>
import { nameCheck } from "@/utils";
import icon_select from "@/components/icon_select.vue";
import setting_domain from "@/components/setting_domain.vue";
import extend_flex from "@/components/extendFlex.vue";
export default {
  components: {
    icon_select,
    setting_domain,
    extend_flex,
  },
  created() {
    if (window.location.href.split("&")[1]) {
      if (window.location.href.split("&")[1].indexOf("obpm") != -1) {
        this.isCanExit = false;
      }
    }
    this.getDomainData(true);
    //关于标题的处理
    this.headerArr = {
      iconfont: "icon-icon_yzh_off",
      content: this.$t("enterprise_info"),
      btnArr: [
        { type: 'primary', name: "save", label: this.$t("save") },
      ],
    }; 
    if(this.$route.query.showLdapButton){
      this.headerArr.btnArr.unshift({type:'primary',name:"syn_ladp",label:this.$t('syn_ladp')})
    }
    if(this.isCanExit){
      this.headerArr.btnArr.push({ name: "exit", label: this.$t("exit") })
    }
  },
  data() {
    return {
      contextPath:this.$api.getContextPath(),
      content: {},
      iconSelectCheck: false,
      domainVisible: false,
      dialogTitle: '',
      domainParentId: '',//获取上级的id
      domainChildId: '',//获取下级的id
      parentList: '',  //获取上级域
      childList: '',   //获取下级域
      logoUrl: "img",
      fieldextends: [],
      fontIconColor: "#000000",
      skins: [],
      options:[],
      radioValue:'',
      selectValue:'',
      superiorTags: [], //上级标签
      childsTags: [], //下级标签
      juniorTags: [],
      rules: {
        name: [
          { required: true, message: "请先填写域(租户)名称", trigger: "blur" },
          {
            validator: nameCheck,
            trigger: "blur",
          },
        ],
      },
      isCanExit: true,
      nowOption:"depImport",
      headerArr:{}
    };
  },
  computed: {
    status: {
      get() {
        return this.content.status == 1;
      },
      set(value) {
        this.content.status = value ? 1 : 0;
      },
    },
  },
  methods: {
    /**
     * 获取企业域信息
     */
    getDomainData(val){
      this.$api.getDomain(this.$route.query.domainid, {
        onSucess: (resp) => {
          this.$store.commit("setDomainName",resp.data.data.name);
          this.content = resp.data.data;
          this.superiorTags = resp.data.data.parents;
          this.childsTags = resp.data.data.childs;
          if(val){
            this.getFieldList();
          }
          if (this.content.logoUrl.indexOf("#") != -1) {
            this.logoUrl = "icon";
            this.fontIconColor = this.content.logoUrl.slice(
              this.content.logoUrl.indexOf("#")
            );
            this.content.logoUrl = this.content.logoUrl.replace(
              /#[0-9a-zA-Z]{6}/,
              ""
            );
          }
          for(let i=0;i<this.fieldextends.length;i++){
            if(this.fieldextends[i].type == "address"){
              let provinceAddress = this.content[this.fieldextends[i].name].split(',')
              let arr = [];
              arr.push(provinceAddress[0],provinceAddress[1],provinceAddress[2])
              this.content[this.fieldextends[i].name] = arr;
              this.content[this.fieldextends[i].name+'_registerAddress'] = provinceAddress[3]
            }
          }
        },
      });
    },
    getFieldList() {
      let that = this;
      let dataJson={ 
        currpage:1,
        pagelines:999,
        data:{
          type:"",
          fortable:"tableDomain",
          domainid: this.$route.query.domainid,
          belong:"All"
        }
      }
      /**
       * 获取字段拓展
       */
      this.$api.getFieldExtends(
        dataJson,
        {
          onSucess: resp => {
            resp.data.data.datas.forEach( elm => {
              if(elm.type == "radio" || elm.type == "select" || elm.type == "checkbox"){
                let option = elm.options.split(";");
                let arr = [];
                if(elm.type == "radio" || elm.type == "select") {
                  for(let i=0;i<option.length;i++){
                    let obj = {}
                    obj.label = option[i];
                    obj.value = option[i];
                    arr.push(obj);
                  }
                  elm.options = arr;
                } else if(elm.type == "checkbox") {
                  elm.checkboxList = that.content[elm.name].split(";");
                  elm.options = option;
                }
              } else if(elm.type == "address") {
                this.content[elm.name+'_registerAddress'] = this.content[elm.name].split(',')[3];
                let arr = [];
                arr.push(this.content[elm.name].split(',')[0],this.content[elm.name].split(',')[1],this.content[elm.name].split(',')[2])
                this.content[elm.name] = arr;
              }
              that.fieldextends.push(elm);
            })
            this.$forceUpdate();
          }
        }
      );
    },
    syncLDAPInfo(){
      this.$api.asyncLDAP(this.$route.query.domainid, {
        onSucess: response => {
          if(response.data.errcode == 0){
            this.$message.success(response.data.errmsg)
          }else{
            this.$message.warning(response.data.errmsg)
          }
        }
      });
    },
    /**
     * 获取上下级数据
     */
    handleClick(){
      let parentsId = "";
      if(this.domainListId){
        parentsId = this.domainListId;
      }else{
        let parents = this.content.parents ? this.content.parents : [];
        parents.map((item)=>{
          if(parentsId){
            parentsId = parentsId + ";" +item.domainid;
          }else{
            parentsId = item.domainid;
          }
        })
      }
      this.parentList = parentsId;
      this.dialogTitle = this.$t('setSuperior');
      this.domainVisible = true;
    },
    /**
     * 删除上下级企业域标签
     */
    handleClose(tagId,type){
      let domainid = this.$route.query.domainid;
      let obj = {
        removeId: tagId,
        belong: type
      }
      this.$api.deleteRelation(domainid,{
          data: obj
        },{
        onSucess: response => {
          if(response.data.errcode == 0){
            this.$message({
              message: response.data.data,
              type: "success",
            });
            this.getDomainData();
          }
        }
      });
    },
    /**
     * 保存上下级返回数据
     */
    selectChecked(val,type){
      let domainid = this.$route.query.domainid;
      this.saveBaseinfo(domainid,val,type);
    },
    onBtnClick(name){
      if(name=='save'){this.onSave('form')}
      else if(name=='syn_ladp'){this.syncLDAPInfo()}
      else if(name=='exit'){this.$router.push({ name: 'main'})}
    },
    /**
     * 保存企业域信息
     */
    saveBaseinfo(domainid,selectValue,type){
      // 判断当前项是否为必填项
      let checkArr = []
      let checkTip = ""
      let have = true
      if(this.fieldextends.length > 0){
        this.fieldextends.map(item => {
          if(item.isNotNull){
            checkArr.push(item)
          }
          if(item.type == "address"){
            this.content[item.name]
            if(this.content[item.name+'_registerAddress']){
              if(typeof(this.content[item.name]) == "string"){
                this.content[item.name] = this.content[item.name] + "," + this.content[item.name+'_registerAddress'];
              }else{
                this.content[item.name].push(this.content[item.name+'_registerAddress'])
              }
            }
            this.content[item.name] = this.content[item.name].toString();
          }
        })
        if(checkArr.length > 0){
          checkArr.some(ele => { if(!this.content[ele.name]){
            have = false
            checkTip += ele.label + ','
          } })
        }
        if(!have){
          this.$message.error(checkTip.substring(0, checkTip.lastIndexOf(',')) + '字段为必填项')
          return false;
        }
      }
      if (domainid) {
        //当是选择上下级时，不需要回到主页
          if(type == "parent"){
            let ChildsId = "";
            let childs = this.content.childs ? this.content.childs : [];
            childs.map((item)=>{
              if(ChildsId){
                ChildsId = ChildsId + ";" +item.domainid;
              }else{
                ChildsId = item.domainid;
              }
            })
            this.domainParentId = selectValue;
            this.domainChildId = ChildsId;
          }else{
            let parentsId = "";
            let parents = this.content.parents;
            parents.map((item)=>{
              if(parentsId){
                parentsId = parentsId + ";" +item.domainid;
              }else{
                parentsId = item.domainid;
              }
            })
            this.domainParentId = parentsId;
            this.domainChildId = selectValue;
          }
        //更新
        let content = {
          ...this.content,
          "description": this.content.description,
          "id": this.content.id,
          "logoUrl": this.content.logoUrl,
          "name": this.content.name,
          "smsMemberCode": this.content.smsMemberCode,
          "smsMemberPwd": this.content.smsMemberPwd,
          "status": this.content.status,
          "systemName": this.content.systemName,
          "isOpenThM":this.content.isOpenThM,//是否开启三员管理
          "users": this.content.users,
          "field1":this.content.field1?this.content.field1:null,
          "field2":this.content.field2?this.content.field2:null,
          "field3":this.content.field3?this.content.field3:null,
          "field4":this.content.field4?this.content.field4:null,
          "field5":this.content.field5?this.content.field5:null,
          "field6":this.content.field6?this.content.field6:null,
          "field7":this.content.field7?this.content.field7:null,
          "field8":this.content.field8?this.content.field8:null,
          "field9":this.content.field9?this.content.field9:null,
          "field10":this.content.field10?this.content.field10:null,
          "field11":this.content.field11?this.content.field11:null,
          "field12":this.content.field12?this.content.field12:null,
          "field13":this.content.field13?this.content.field13:null,
          "field14":this.content.field14?this.content.field14:null,
          "field15":this.content.field15?this.content.field15:null,
          "field16":this.content.field16?this.content.field16:null,
          "field17":this.content.field17?this.content.field17:null,
          "field18":this.content.field18?this.content.field18:null,
          "field19":this.content.field19?this.content.field19:null,
          "field20":this.content.field20?this.content.field20:null,
          "parents":this.domainParentId?this.domainParentId:[],
          "childs":this.domainChildId?this.domainChildId:[]
        }
        this.$api.updateDomain(domainid, content, {
          onSucess: (resp) => {
            if (resp && resp.data.errcode == 0) {
              this.$store.commit("setDomainName",resp.data.data.name);
              this.$message({
                showClose: true,
                message: this.$t('msg_save_success'),
                type: "success",
              });
              if (this.isCanExit) {
                this.getDomainData();
                // this.$router.push({ name: "main" });
                // 修改为请求

              }else if(this.domainListId !=""){
                this.getDomainData();
              }
            } else {
              this.$message({
                message: resp.data.errmsg,
                type: "error",
              });
            }
          },
        });
      } else {
        //新建
        let content = {
          ...this.content,
          "description": this.content.description,
          "id": this.content.id,
          "logoUrl": this.content.logoUrl,
          "name": this.content.name,
          "smsMemberCode": this.content.smsMemberCode,
          "smsMemberPwd": this.content.smsMemberPwd,
          "status": this.content.status,
          "systemName": this.content.systemName,
          "isOpenThM":this.content.isOpenThM,
          "users": this.content.users,
          "field1":this.content.field1?this.content.field1:null,
          "field2":this.content.field2?this.content.field2:null,
          "field3":this.content.field3?this.content.field3:null,
          "field4":this.content.field4?this.content.field4:null,
          "field5":this.content.field5?this.content.field5:null,
          "field6":this.content.field6?this.content.field6:null,
          "field7":this.content.field7?this.content.field7:null,
          "field8":this.content.field8?this.content.field8:null,
          "field9":this.content.field9?this.content.field9:null,
          "field10":this.content.field10?this.content.field10:null,
          "field11":this.content.field11?this.content.field11:null,
          "field12":this.content.field12?this.content.field12:null,
          "field13":this.content.field13?this.content.field13:null,
          "field14":this.content.field14?this.content.field14:null,
          "field15":this.content.field15?this.content.field15:null,
          "field16":this.content.field16?this.content.field16:null,
          "field17":this.content.field17?this.content.field17:null,
          "field18":this.content.field18?this.content.field18:null,
          "field19":this.content.field19?this.content.field19:null,
          "field20":this.content.field20?this.content.field20:null,
          "parents":selectValue?selectValue:[],
        }
        this.$api.createDomain(content, {
          onSucess: (resp) => {
            if (resp && resp.data.errcode == 0) {
              this.$message({
                message: this.$t('msg_save_success'),
                type: "success",
              });
              this.getDomainData();
              // this.$router.push({ name: "main" });
            } else {
              this.$message({
                message: resp.data.errmsg,
                type: "error",
              });
            }
          },
        });
      }
    },
    onSave(formName) {
      let domainid = this.$route.query.domainid;
      if (this.logoUrl == "icon") {
        this.content.logoUrl = this.content.logoUrl + this.fontIconColor;
      }
      // 判断当前项是否为必填项
      let checkArr = []
      let checkTip = ""
      let have = true
      if(this.fieldextends.length > 0){
        this.fieldextends.map(item => {
          if(item.isNotNull){
            checkArr.push(item)
          }
        })
        if(checkArr.length > 0){
          checkArr.some(ele => { if(!this.content[ele.name]){
            have = false
            checkTip += ele.label + ','
          } })
        }
        if(!have){
          this.$message.error(checkTip.substring(0, checkTip.lastIndexOf(',')) + '字段为必填项')
          return false;
        }
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveBaseinfo(domainid)
        }
      });
    },
    testSMS() {
      this.$prompt(this.$t('msg_require_tel'), this.$t('msg_tip'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        inputPattern: /^1\d{10}$/,
        inputErrorMessage: this.$t("msg_incorrect_phone"),
      })
        .then(({ value }) => {
          this.$api.testSMS(this.content.id, value, {
            onSucess: (resp) => {
              if (resp && resp.data.data.type == "success") {
                this.$message({
                  message: this.$t("msg_send_success"),
                  type: "success",
                });
              } else {
                this.$message({
                  message: resp.data.data.message,
                  type: "error",
                });
              }
            },
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("msg_cancel"),
          });
        });
    },
    selectIcon() {
      this.iconSelectCheck = true;
    },
    cleanIcon() {
      this.content.logoUrl = "";
    },
    onSelectIconOk(item) {
      if (item) {
        if (item.path) {
          this.logoUrl = "img";
          this.content.logoUrl = this.$api.getLogoUrl(item.path);
        } else if (item.filePath) {
          this.logoUrl = "img";
          this.content.logoUrl = this.$api.getLogoUrl(item.filePath);
        } else {
          this.$message({
            type: "error",
            message: "选择失败",
          });
        }
      }
    },
  },
};
</script>
<style scoped>
@import "../assets/css/font-awesome.min.css";
</style>
<style lang="scss" scoped>
</style>